package com.example.voucher.config;

import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.example.voucher.config.third.TenantThirdAccountBO;
import com.example.voucher.config.third.ThirdAccountBean;
import com.google.common.collect.Maps;

@Component
public class ThirdAccountRegister {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThirdAccountRegister.class);

    @Value("${current.setting.name:}")
    private String env;

    @Autowired
    private ThirdAccountBean accountBean;
    @Autowired
    private TenantMirrorConfig mirrorConfig;

    // R为tenantCode C为凭证场景 V为科目相关配置
    private Map<String, TenantThirdAccountBO> accountMap = Maps.newHashMap();

    public TenantThirdAccountBO getAccountConfig(String tenantCode) {
        // 优先使用nacos上最新的配置
        if (MapUtils.isNotEmpty(accountBean.getTenantMap())) {
            accountMap.putAll(accountBean.getTenantMap());
        }
        TenantThirdAccountBO bo = accountMap.get(tenantCode);
        if (bo == null) {
            String mirrorTenantCode = mirrorConfig.getMirror(tenantCode);
            if (StringUtils.isNotBlank(mirrorTenantCode) && accountMap.containsKey(mirrorTenantCode)) {
                LOGGER.warn("找不到租户=【{}】推送第三方凭证登录账户相关的配置，模拟租户【{}】", tenantCode, mirrorTenantCode);
                bo = accountMap.get(mirrorTenantCode);
            }
        }
        if (bo == null) {
            throw new RuntimeException(String.format("找不到租户=【{%s}】推送第三方凭证登录账户相关的配置", tenantCode));
        }
        return bo;
    }

    public void registerLocalAccountConfig(String env, ThirdAccountBean bo) {
        if (this.env.equals(env) || StringUtils.isBlank(env)) {
            accountMap.putAll(bo.getTenantMap());
        }
    }

}
